package com.djq.hhc.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.djq.hhc.dto.UserInfoDto;
import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.jwt.JwtUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.djq.hhc.redis.RedisConstants.LOGIN_TOKEN_KEY;
import static com.djq.hhc.redis.RedisConstants.LOGIN_TOKEN_TTL;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/02/27/下午 3:18
 * @Description:
 */
public class RefreshInterceptor implements HandlerInterceptor {

    //这个类不是spring创建的，是手动创建的，不能使用注入注解
    private StringRedisTemplate stringRedisTemplate;
    //构造函数
    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");
        //token是否为空
        if (StrUtil.isBlank(token)) {
            return true;
        }
//        //token是否有效
//        boolean verifyToken = JwtUtils.verifyToken(token);
//        if (!verifyToken) {
//            return true;
//        }
        //基于Token获取redis中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(LOGIN_TOKEN_KEY + token);
        //判断user是否为空
        if (userMap.isEmpty()) {
            return true;
        }
        //转为userDTO,最后一个false是 是否忽略转换中的错误
        UserInfoDto userDTO = BeanUtil.fillBeanWithMap(userMap, new UserInfoDto(), true);
        //存在，保存用户信息到线程
        UserHolder.saveUser(userDTO);
        //创建token有效期
        stringRedisTemplate.expire(LOGIN_TOKEN_KEY + token,LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
